package com.xdemo.personal.socketclient;

import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;

import com.xdemo.core.MessageType;
import com.xdemo.personal.socketserver.msg.BasePlayerMessage;
import com.xdemo.personal.socketserver.msg.QueryResultMessage;
import com.xdemo.personal.socketserver.msg.ResultFoundMessage;
import com.xdemo.personal.socketserver.msg.StoreMessage;
import com.xdemo.personal.socketserver.msg.StoreSuccessMsg;

public class SimpleClientHandler extends SimpleChannelUpstreamHandler {

	@Override
	public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
			throws Exception {
		if(e.getMessage() == null || !(e.getMessage() instanceof BasePlayerMessage)) {
			return;
		}
		switch(((BasePlayerMessage)e.getMessage()).getType()) {
		case MessageType.StoreSuccess:
			StoreSuccessMsg _sucMsg = (StoreSuccessMsg)e.getMessage();
			QueryResultMessage _queryMsg = new QueryResultMessage(_sucMsg.getStoreKey());
			ctx.getChannel().write(_queryMsg);
			break;
		case MessageType.Result:
			ResultFoundMessage _msg = (ResultFoundMessage)e.getMessage();
			System.out.println(_msg.getKey() + "==>" + _msg.getResult());
			break;
		}
	}

	@Override
	public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e)
			throws Exception {
		for(int i=0;i<1000;i++) {
			StoreMessage _msg = new StoreMessage();
			_msg.setStoreKey(i);
			e.getChannel().write(_msg);
		}
	}
	
}
